package com.hyacinth.forumbite.exception;

import com.hyacinth.forumbite.common.AppResult;
import com.hyacinth.forumbite.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 * @Author: Yun
 * @Date: 2025/5/16
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationResultHandler(ApplicationException e){
        e.printStackTrace();
        log.error(e.getMessage());
        if (e.getErrorResult() != null){
            return e.getErrorResult();
        }
        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult exceptionHandler(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(e.getMessage());
    }
}
